﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TimberSmart.Data.Contracts;
using TimberSmart.Model.Security;

namespace TimberSmart.Data.Repositories
{
    public class UserRepository : RepositoryBase, IUserRepository
    {
        public UserRepository(DbContext context)
            : base(context)
        {
        }

        public IEnumerable<User> FindAllUsers()
        {
            return FindAll<User>().ToList();
        }

        public User FindUserByUsername(string username)
        {
            var result = _context.Set<User>()
                .Where(a => a.Username == username);

            return result.SingleOrDefault();
        }

        public User FindUserByCredentials(string username, byte[] passwordHash)
        {
            var result = _context.Set<User>()
                .Where(a => a.Username == username && a.PasswordHash == passwordHash);

            return result.SingleOrDefault();
        }

        public IEnumerable<Menu> FindMenusForUser(int userId)
        {
            var result = _context.Set<Menu>()
                .Where(a => a.Roles
                    .Any(b => b.Users
                        .Any(c => c.Id == userId)
                    )
                ).ToList();

            var filteredResult = result.Where(a => a.Parent == null);

            foreach (Menu m in filteredResult)
            {
                m.Parent = null;
            }

            return filteredResult;
        }

        public void AddUser(User user)
    {
            Add<User>(user);
        }

        public void UpdateUser(User user)
        {
            Update<User>(user);
        }

        public void DeleteUser(User user)
        {
            Delete<User>(user);
        }

        public void DeleteUser(int id)
        {
            Delete<User>(id);
        } 
    }
}
